//
//  Board.m
//  billiards
//
//  Created by Matsumae Kentaro on 12/03/22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Board.h"
#import "Ball.h"
#import "MenuGame.h"

enum {
    kBoardCertGroupWall,
    kBoardCertGroupHall,
    kBoardCertGroupBall
};

@interface Board (Private)
-(void)setup;
@end

@implementation Board

@synthesize countBallBlue,countBallRed,lbMoveUser,redHadShoot;

-(void) fadeInLabel{
    [lbMoveUser runAction:[CCSequence actions:[CCFadeIn actionWithDuration:0.5],[CCCallFunc actionWithTarget:self selector:@selector(fadeOutLabel)], nil]];
}

-(void) fadeOutLabel{
    [lbMoveUser runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFunc actionWithTarget:self selector:@selector(fadeInLabel)], nil]];
}

-(id)initWithWorld:(b2World*)world {
    if ((self = [super init])) {
        world_ = world;
        
        CCSprite* board = [CCSprite spriteWithFile:@"gamebg.png"];
        board.position = [Helper screenCenter];
        board.scaleX = 0.78;
        board.scaleY = 0.81;
        [self addChild:board];
        
        countBallRed = 7;
        countBallBlue = 7;
        
        [self setup];
        
        lbMoveUser = [[CCLabelTTF alloc] initWithString:@"Blue Move" dimensions:CGSizeMake(200, 40) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:20];
        lbMoveUser.color = ccBLUE;
        lbMoveUser.position = ccp(410,210);
        [self addChild:lbMoveUser];
        
        lbWinUser = [[CCLabelTTF alloc] initWithString:@"Blue Win" dimensions:CGSizeMake(320, 40) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:40];
        lbWinUser.color = ccBLUE;
        lbWinUser.position = ccp(160,175);
        lbWinUser.visible = NO;
        lbWinUser.scale = 0.1;
        [self addChild:lbWinUser];
        
        [lbMoveUser runAction:[CCSequence actions:[CCFadeOut actionWithDuration:0.5],[CCCallFunc actionWithTarget:self selector:@selector(fadeInLabel)], nil]];
        
        b1 = [CCSprite spriteWithFile:@"blue_ball.png"];
        b1.position = ccp(365,80);
        b1.visible = NO;
        [self addChild:b1];
        
        b2 = [CCSprite spriteWithFile:@"blue_ball.png"];
        b2.position = ccp(405,80);
        b2.visible = NO;
        [self addChild:b2];
        
        b3 = [CCSprite spriteWithFile:@"blue_ball.png"];
        b3.position = ccp(445,80);
        b3.visible = NO;
        [self addChild:b3];
        
        br1 = [CCSprite spriteWithFile:@"red_ball.png"];
        br1.position = ccp(365,153);
        br1.visible = NO;
        [self addChild:br1];
        
        br2 = [CCSprite spriteWithFile:@"red_ball.png"];
        br2.position = ccp(405,153);
        br2.visible = NO;
        [self addChild:br2];
        
        br3 = [CCSprite spriteWithFile:@"red_ball.png"];
        br3.position = ccp(445,153);
        br3.visible = NO;
        [self addChild:br3];
        
        redHadShoot = NO;
    }
    return self;
}

+(id) setupBoradWithWorld:(b2World*)world {
    return [[[Board alloc] initWithWorld:world] autorelease];
}

-(void) createStaticBodyWithVertices:(b2Vec2[])vertices numVertices:(int)numVertices {
	// Create a body definition 
	b2BodyDef bodyDef;
	bodyDef.position = [Helper toMeters:CGPointMake(0, 0)];
	
	b2PolygonShape shape;
	shape.Set(vertices, numVertices);
	
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &shape;
	fixtureDef.density = 1.0f;
	fixtureDef.friction = 0.2f;
	fixtureDef.restitution = 0.1f;
	
	b2Body* body = world_->CreateBody(&bodyDef);
	body->CreateFixture(&fixtureDef);
}

static const ccColor3B ccBRAWN = {110,0,0};

static ccColor3B ballColors[15] = {
    //1列目
    ccYELLOW,
    //2列目
    ccGREEN,
    ccORANGE,
    ccGREEN,
    ccBLACK,
    ccBLUE,
    //4列目
    ccORANGE,
    ccBRAWN,
    ccBRAWN,
    ccRED,
    //5列目
    ccORANGE,
    ccMAGENTA,
    ccMAGENTA,
    ccRED,
    ccBLUE,
};

-(void)setup {
    [self setupAll:YES];
}

-(b2Body *) getCurrentBodyByTag:(int) tag{
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *ballData = (CCSprite *)b->GetUserData();
            if (ballData.tag==tag) {
                return b;
            }
        }        
    }
    return nil;
}

-(b2World *) getWorld{
    return world_;
}

-(void) hideLabelWin{
    lbWinUser.visible = NO;
    lbWinUser.scale = 0.1;
}

-(void) doMarkGame:(int) markType{
    if (markType==1) {
        currentBlueMark++;
        if (currentBlueMark==1) {
            b1.visible = YES;
            b2.visible = NO;
            b3.visible = NO;
        }
        else if (currentBlueMark==2) {
            b1.visible = YES;
            b2.visible = YES;
            b3.visible = NO;
        }
        else if (currentBlueMark==3) {
            b1.visible = YES;
            b2.visible = YES;
            b3.visible = YES;
        }
        moveFirst = 2;
        
        [lbWinUser setString:@"Blue Win"];
        lbWinUser.color = ccBLUE;
        lbWinUser.visible = YES;
   
        [lbWinUser runAction:[CCSequence actions:[CCSpawn actions:[CCScaleTo actionWithDuration:1.5 scale:5],[CCFadeOut actionWithDuration:1.5], nil],[CCCallFunc actionWithTarget:self selector:@selector(hideLabelWin)], nil]];
    }
    else {
        currentRedMark++;
        if (currentRedMark==1) {
            br1.visible = YES;
            br2.visible = NO;
            br3.visible = NO;
        }
        else if (currentRedMark==2) {
            br1.visible = YES;
            br2.visible = YES;
            br3.visible = NO;
        }
        else if (currentRedMark==3) {
            br1.visible = YES;
            br2.visible = YES;
            br3.visible = YES;
        }
        moveFirst = 1;
        
        [lbWinUser setString:@"Red Win"];
        lbWinUser.color = ccRED;
        lbWinUser.visible = YES;
        [lbWinUser runAction:[CCSequence actions:[CCSpawn actions:[CCScaleTo actionWithDuration:1.5 scale:5],[CCFadeOut actionWithDuration:1.5], nil],[CCCallFunc actionWithTarget:self selector:@selector(hideLabelWin)], nil]];
    }
    
    if (currentBlueMark==3) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over" message:@"Blue ball is WINNER!!!" delegate:self cancelButtonTitle:@"Home" otherButtonTitles:@"Try Again", nil];
        [alert show];
        [alert release];
    }
    if (currentRedMark==3) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over" message:@"Red ball is WINNER!!!" delegate:self cancelButtonTitle:@"Home" otherButtonTitles:@"Try Again", nil];
        [alert show];
        [alert release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [[CCDirector sharedDirector] replaceScene:[CCTransitionMoveInL transitionWithDuration:0.5 scene:[MenuGame scene]]];
    }
    else if (buttonIndex==1) {
        currentRedMark = 0;
        currentBlueMark = 0;
        
        [self resetAllBall];
        
        b1.visible = NO;
        b2.visible = NO;
        b3.visible = NO;
        
        br1.visible = YES;
        br2.visible = NO;
        br3.visible = NO;
    }
}

-(void) resetAllBall{
    NSMutableArray* ary = [[[NSMutableArray alloc] init] autorelease];
    for (CCNode* node in self.children) {
        if ([node isKindOfClass:[Ball class]]) {
            [ary addObject:node];
        }
    }
    for (CCNode* ball in ary) {
        [ball stopAllActions];
        [(Ball *) ball removeTouchDelete];
        [self removeChild:ball cleanup:YES];
    }
    [self setupAll:NO];
}

-(void)setupAll:(BOOL)setupAll {
    if (currentBlueMark==currentRedMark && currentRedMark==0) {
        moveFirst = 1;
    }
    if (currentBlueMark==0) {
        Ball* ballB1 = [Ball ballWithWorld:world_ at:ccp(35, 45) touchable:YES type:1];
        ballB1.tag = 1;
        [self addChild:ballB1];
        
        Ball* ballB2 = [Ball ballWithWorld:world_ at:ccp(75, 45) touchable:YES type:1];
        ballB2.tag = 2;
        [self addChild:ballB2];
        
        Ball* ballB3 = [Ball ballWithWorld:world_ at:ccp(115, 45) touchable:YES type:1];
        ballB3.tag = 3;
        [self addChild:ballB3];
        
        Ball* ballB4 = [Ball ballWithWorld:world_ at:ccp(155, 45) touchable:YES type:1];
        ballB4.tag = 4;
        [self addChild:ballB4];
        
        Ball* ballB5 = [Ball ballWithWorld:world_ at:ccp(195, 45) touchable:YES type:1];
        ballB5.tag = 5;
        [self addChild:ballB5];
        
        Ball* ballB6 = [Ball ballWithWorld:world_ at:ccp(235, 45) touchable:YES type:1];
        ballB6.tag = 6;
        [self addChild:ballB6];
        
        Ball* ballB7 = [Ball ballWithWorld:world_ at:ccp(275, 45) touchable:YES type:1];
        ballB7.tag = 7;
        [self addChild:ballB7];
    }
    else if (currentBlueMark==1) {
        Ball* ballB1 = [Ball ballWithWorld:world_ at:ccp(55, 80) touchable:YES type:1];
        ballB1.tag = 1;
        [self addChild:ballB1];
        
        Ball* ballB2 = [Ball ballWithWorld:world_ at:ccp(95, 80) touchable:YES type:1];
        ballB2.tag = 2;
        [self addChild:ballB2];
        
        Ball* ballB3 = [Ball ballWithWorld:world_ at:ccp(135, 80) touchable:YES type:1];
        ballB3.tag = 3;
        [self addChild:ballB3];
        
        Ball* ballB4 = [Ball ballWithWorld:world_ at:ccp(175, 80) touchable:YES type:1];
        ballB4.tag = 4;
        [self addChild:ballB4];
        
        Ball* ballB5 = [Ball ballWithWorld:world_ at:ccp(215, 80) touchable:YES type:1];
        ballB5.tag = 5;
        [self addChild:ballB5];
        
        Ball* ballB6 = [Ball ballWithWorld:world_ at:ccp(255, 80) touchable:YES type:1];
        ballB6.tag = 6;
        [self addChild:ballB6];
        
        Ball* ballB7 = [Ball ballWithWorld:world_ at:ccp(1000, 1000) touchable:YES type:1];
        ballB7.tag = 7;
        [self addChild:ballB7];
    }
    else if (currentBlueMark==2) {
        Ball* ballB1 = [Ball ballWithWorld:world_ at:ccp(75, 115) touchable:YES type:1];
        ballB1.tag = 1;
        [self addChild:ballB1];
        
        Ball* ballB2 = [Ball ballWithWorld:world_ at:ccp(115, 115) touchable:YES type:1];
        ballB2.tag = 2;
        [self addChild:ballB2];
        
        Ball* ballB3 = [Ball ballWithWorld:world_ at:ccp(155, 115) touchable:YES type:1];
        ballB3.tag = 3;
        [self addChild:ballB3];
        
        Ball* ballB4 = [Ball ballWithWorld:world_ at:ccp(195, 115) touchable:YES type:1];
        ballB4.tag = 4;
        [self addChild:ballB4];
        
        Ball* ballB5 = [Ball ballWithWorld:world_ at:ccp(235, 115) touchable:YES type:1];
        ballB5.tag = 5;
        [self addChild:ballB5];
        
        Ball* ballB6 = [Ball ballWithWorld:world_ at:ccp(1000, 1000) touchable:YES type:1];
        ballB6.tag = 6;
        [self addChild:ballB6];
        
        Ball* ballB7 = [Ball ballWithWorld:world_ at:ccp(1000, 1000) touchable:YES type:1];
        ballB7.tag = 7;
        [self addChild:ballB7];
    }
    
    if (currentRedMark==0) {
        Ball* ballR1 = [Ball ballWithWorld:world_ at:ccp(35, 280) touchable:YES type:2];
        ballR1.tag = 8;
        [self addChild:ballR1];
        
        Ball* ballR2 = [Ball ballWithWorld:world_ at:ccp(75, 280) touchable:YES type:2];
        ballR2.tag = 9;
        [self addChild:ballR2];
        
        Ball* ballR3 = [Ball ballWithWorld:world_ at:ccp(115, 280) touchable:YES type:2];
        ballR3.tag = 10;
        [self addChild:ballR3];
        
        Ball* ballR4 = [Ball ballWithWorld:world_ at:ccp(155, 280) touchable:YES type:2];
        ballR4.tag = 11;
        [self addChild:ballR4];
        
        Ball* ballR5 = [Ball ballWithWorld:world_ at:ccp(195, 280) touchable:YES type:2];
        ballR5.tag = 12;
        [self addChild:ballR5];
        
        Ball* ballR6 = [Ball ballWithWorld:world_ at:ccp(235, 280) touchable:YES type:2];
        ballR6.tag = 13;
        [self addChild:ballR6];
        
        Ball* ballR7 = [Ball ballWithWorld:world_ at:ccp(275, 280) touchable:YES type:2];
        ballR7.tag = 14;
        [self addChild:ballR7];
    }
    else if (currentRedMark==1) {
        Ball* ballR1 = [Ball ballWithWorld:world_ at:ccp(55, 245) touchable:YES type:2];
        ballR1.tag = 8;
        [self addChild:ballR1];
        
        Ball* ballR2 = [Ball ballWithWorld:world_ at:ccp(95, 245) touchable:YES type:2];
        ballR2.tag = 9;
        [self addChild:ballR2];
        
        Ball* ballR3 = [Ball ballWithWorld:world_ at:ccp(135, 245) touchable:YES type:2];
        ballR3.tag = 10;
        [self addChild:ballR3];
        
        Ball* ballR4 = [Ball ballWithWorld:world_ at:ccp(175, 245) touchable:YES type:2];
        ballR4.tag = 11;
        [self addChild:ballR4];
        
        Ball* ballR5 = [Ball ballWithWorld:world_ at:ccp(215, 245) touchable:YES type:2];
        ballR5.tag = 12;
        [self addChild:ballR5];
        
        Ball* ballR6 = [Ball ballWithWorld:world_ at:ccp(255, 245) touchable:YES type:2];
        ballR6.tag = 13;
        [self addChild:ballR6];
        
        Ball* ballR7 = [Ball ballWithWorld:world_ at:ccp(-1000, -1000) touchable:YES type:2];
        ballR7.tag = 14;
        [self addChild:ballR7];
    }
    else if (currentRedMark==2) {
        Ball* ballR1 = [Ball ballWithWorld:world_ at:ccp(75, 215) touchable:YES type:2];
        ballR1.tag = 8;
        [self addChild:ballR1];
        
        Ball* ballR2 = [Ball ballWithWorld:world_ at:ccp(115, 215) touchable:YES type:2];
        ballR2.tag = 9;
        [self addChild:ballR2];
        
        Ball* ballR3 = [Ball ballWithWorld:world_ at:ccp(155, 215) touchable:YES type:2];
        ballR3.tag = 10;
        [self addChild:ballR3];
        
        Ball* ballR4 = [Ball ballWithWorld:world_ at:ccp(195, 215) touchable:YES type:2];
        ballR4.tag = 11;
        [self addChild:ballR4];
        
        Ball* ballR5 = [Ball ballWithWorld:world_ at:ccp(235, 215) touchable:YES type:2];
        ballR5.tag = 12;
        [self addChild:ballR5];
        
        Ball* ballR6 = [Ball ballWithWorld:world_ at:ccp(-1000, -1000) touchable:YES type:2];
        ballR6.tag = 13;
        [self addChild:ballR6];
        
        Ball* ballR7 = [Ball ballWithWorld:world_ at:ccp(-1000, -1000) touchable:YES type:2];
        ballR7.tag = 14;
        [self addChild:ballR7];
    }
    
    NSMutableArray* ary = [[[NSMutableArray alloc] init] autorelease];
    for (CCNode* node in self.children) {
        if ([node isKindOfClass:[Ball class]]) {
            [ary addObject:node];
        }
    }
    for (CCNode* ball in ary) {
        ((Ball *) ball).moveUser = moveFirst;
    }
    
    if (moveFirst==1) {
        [lbMoveUser setString:@"Blue Move"];
    }
    else {
        [lbMoveUser setString:@"Red Move"];
    }
}

-(void)resetBalls {
    NSMutableArray* ary = [[[NSMutableArray alloc] init] autorelease];
    for (CCNode* node in self.children) {
        if ([node isKindOfClass:[Ball class]]) {
            [ary addObject:node];
        }
    }
    for (CCNode* ball in ary) {
        [self removeChild:ball cleanup:YES];
    }
    [self setupAll:NO];
    
    countBallRed = 7;
    countBallBlue = 7;
}

-(BOOL)isInHall:(CGPoint)pos {
    if (pos.x<=0 || pos.x>=320) {
        return YES;
    }
    if (pos.y<=0 || pos.y>=320) {
        return YES;
    }
    return NO;
}

-(void) autoRedShoot{
    b2Body *red = nil;
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *tempSprite = (CCSprite *) b->GetUserData();
            if (tempSprite.visible==YES && tempSprite.tag>7) {
                red = b;
                break;
            }
        }        
    }
    b2Body *blue = nil;
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            CCSprite *tempSprite = (CCSprite *) b->GetUserData();
            if (tempSprite.visible==YES && tempSprite.tag<=7) {
                blue = b;
                break;
            }
        }        
    }
    if (red && blue) {
        b2Vec2 bluePos = blue->GetWorldCenter();
        b2Vec2 redPos = red->GetWorldCenter();
        
        b2Vec2 bodyToMove = bluePos - redPos;
//        if (bluePos.y>redPos.y) {
//            bodyToMove = redPos - bluePos;
//        }
        
        b2Vec2 force = 1.5 * bodyToMove;
        
        //red->ApplyForce(force, red->GetWorldCenter());
        red->SetLinearVelocity(force);
        red->SetAngularVelocity(0.0f);
    }
    
    redHadShoot = YES;
    
    [self schedule:@selector(checkBallNotMove)];
}

-(void) checkBallNotMove{
    BOOL can = YES;
    for(b2Body *b = world_->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {
            if((b->IsAwake()))
            {
                can = NO;
            }
        }        
    }
    if (can) {
        redHadShoot = NO;
        [self unschedule:@selector(checkBallNotMove)];
        
        for (CCNode* node in [self children]) {
            if ([node isKindOfClass:[Ball class]]) {
                Ball* ball = (Ball*)node;
                ball.moveUser = 1;
            }
        }
    }
}

@end
